<template>
    <div class="customBox">
        <h3 class="title">
            <el-input v-model="searchKey" clearable placeholder="关键字"></el-input>
            <el-button class="addButton" style="margin: 0 0 0 20px;" type="primary" size="mini" round @click="refresh"
                circle title="刷新">
                <i class="el-icon-refresh"></i>
            </el-button>
            <el-button class="addButton" type="success" size="mini" round @click="addHeaderKey" circle title="添加">
                <i class="el-icon-plus"></i>
            </el-button>
        </h3>

        <div class="customBox-body">
            <div class="empty" v-if="!items.length">
                暂无数据
            </div>

            <el-card style="margin:0 0 10px 0" v-for="item in items" :key="item.urlId">
                <div slot="header" class="clearfix">
                    <span class="text">{{item.title}}</span>
                    <el-button class="deleteButton" type="danger" @click="deleteItem(item)" icon="el-icon-delete"
                        size="mini" circle title="删除">
                    </el-button>
                    <el-button class="editButton" type="primary" @click="editItem(item)" icon="el-icon-edit" size="mini"
                        circle title="编辑">
                    </el-button>
                </div>
                <div class="text">
                    <span>{{item.type + item.str + (item.port == 80 ? '' : ':' + item.port)}}</span>
                    <el-button v-if="!item.loading" style="float: right;" @click="ping(item)" type="primary"
                        size="mini">
                        Ping
                    </el-button>
                    <el-button v-if="item.loading" style="float: right;" @click="item.loading.kill()" type="danger"
                        size="mini">
                        Stop
                    </el-button>
                    <div class="ping" v-html="item.ping"></div>
                    <el-button type="danger" size="mini" v-if="item.close" @click="item.ping = '';item.close = false">
                        clear
                    </el-button>
                </div>
            </el-card>
        </div>


        <el-dialog :title="ruleForm.id ? '编辑URL' : '新建URL'" :close-on-click-modal="false" destroy-on-close
            append-to-body :visible.sync="showEditor" width="500px">
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="demo-ruleForm">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="ruleForm.title"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="str">
                    <el-input v-model="ruleForm.str" class="urlInputSelect">
                        <template slot="prepend">
                            <el-form-item>
                                <el-select style="width: 100px;" v-model="ruleForm.type" placeholder="请选择">
                                    <el-option v-for="item in options" :key="item.value" :label="item.value"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="端口" prop="port">
                    <el-input v-model.number="ruleForm.port"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    import { mapState } from 'vuex';

    const child_process = require('child_process');
    const iconv = require('iconv-lite');


    export default {
        data() {
            return {
                searchKey: '',
                showEditor: false,
                options: [
                    { value: 'http://' },
                    { value: 'https://' },
                ],
                ruleForm: {
                    id: null,
                    type: 'http://',
                    title: '',
                    str: '',
                    port: '80',
                },
                rules: {
                    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
                    str: [{ required: true, message: '请输入地址', trigger: 'blur' }],
                    port: [{ required: true, message: '端口', trigger: 'blur' }],
                },
            }
        },
        computed: {
            ...mapState("url", {
                urlArray: state => state.urlArray,
            }),
            items: function () {
                let _search = this.searchKey;
                let reg = new RegExp(_search, 'ig'); // 不区分大小写
                if (_search) {
                    return this.urlArray.filter(function (item) {
                        if (item.title.toString().match(reg) || item.str.toString().match(reg) || item.port.toString().match(reg)) {
                            return item;
                        }
                    });
                }
                return this.urlArray;
            },
        },
        methods: {
            refresh() {
                this.$store.dispatch('url/getRenderData');
            },
            ping(item) {
                item.close = false;
                item.ping = '';
                item.loading = child_process.spawn('ping', [item.str]);
                item.loading.stdout.on('data', function (data) {
                    var text = iconv.decode(data, 'cp936') + '<br>';
                    text = text.replace('\n\r', '<br>');
                    text = text.replace('统计信息:', '统计信息:<br>');
                    text = text.replace('数据包:', '&nbsp;&nbsp;&nbsp;&nbsp;数据包:<br>');
                    text = text.replace('丢失)，', '丢失)，<br>');
                    text = text.replace('往返行程的估计时间(以毫秒为单位):', '&nbsp;&nbsp;&nbsp;&nbsp;往返行程的估计时间(以毫秒为单位):<br>');
                    item.ping += text;
                });
                item.loading.on('close', function (error, data) {
                    item.loading = false;
                    item.close = true;
                });
            },
            addHeaderKey() {
                this.ruleForm = {
                    id: null,
                    type: 'http://',
                    title: '',
                    str: '',
                    port: '80',
                };
                this.showEditor = true;
            },
            deleteItem(item) {
                var confirm = this.$confirm('是否删除URL？');
                if (confirm) {
                    this.$store.dispatch('url/deleteUrl', item.urlId);
                };
            },
            editItem(item) {
                var _item = JSON.parse(JSON.stringify(item));
                this.ruleForm = {
                    id: _item.urlId,
                    title: _item.title,
                    type: _item.type,
                    str: _item.str,
                    port: _item.port,
                };
                this.showEditor = true;
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (!this.ruleForm.id) {
                            var confirm = this.$confirm('是否创建URL？');
                            if (confirm) {
                                this.$store.dispatch('url/creatUrl', this.ruleForm);
                                this.showEditor = false;
                            };
                        } else {
                            var confirm = this.$confirm('是否更新URL？');
                            if (confirm) {
                                this.$store.dispatch('url/updateUrl', this.ruleForm);
                                this.showEditor = false;
                            };
                        }
                    } else {
                        // console.log('error submit!!');
                        return false;
                    }
                });
            },
        },
    }
</script>
<style scoped>
    .DeleteButton {
        margin: 5px 0 0 10px;
        float: right;
    }

    .title {
        display: flex;
        height: 40px;
        align-items: center;
    }

    .text {
        color: #666;
        line-height: 28px;
    }

    .empty {
        text-align: center;
        line-height: 100px;
        color: #aaa;
    }

    .addButton {
        width: 28px;
        height: 28px;
    }

    .deleteButton {
        float: right;
    }

    .editButton {
        float: right;
        margin: 0 10px 0 0;
    }

    .headerItem {
        margin: 0 0 10px 0;
    }

    .ping {
        margin: 10px 0 5px 0;
        font-size: 12px;
        color: #999;
        line-height: 20px;
    }
</style>